package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult login(WmLoginDto dto) {
       //TODO
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.<WmUser>lambdaQuery()
                .eq(WmUser::getName,dto.getName());
        WmUser user = wmUserMapper.selectOne(wrapper);
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        if(!BCrypt.checkpw(dto.getPassword(),user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken(user.getId().longValue());
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}